#!/usr/bin/env python
#coding: utf-8
from flask import Flask
from flask import url_for, redirect, render_template
from flask_sqlalchemy import SQLAlchemy
from flask_bootstrap import Bootstrap
from flask_assets import Bundle, Environment
from wtforms import StringField, FileField, IntegerField
from wtforms.validators import DataRequired
from flask_wtf import FlaskForm

import colorlog
import logging

logging.basicConfig(level=logging.DEBUG)

handler = colorlog.StreamHandler()
handler.setFormatter(colorlog.ColoredFormatter(
	'%(log_color)s%(levelname)s:%(name)s:%(message)s'))
logger = colorlog.getLogger('example')
logger.addHandler(handler)


app = Flask(__name__)
app.config.from_pyfile('app.config')
db = SQLAlchemy(app)


class UserForm(FlaskForm):
    name = StringField('name', validators=[DataRequired()])
    number = IntegerField('number', validators=[DataRequired()])
    email = StringField('email', validators=[DataRequired()])
    address = StringField('address', validators=[DataRequired()])


class SearchForm(FlaskForm):
    search = StringField('search', validators=[DataRequired()])

class User(db.Model):
    __tablename__ = 'user'
    id = db.Column('id', db.Integer, primary_key=True)
    name = db.Column(db.String(255))
    number = db.Column(db.Integer)
    email = db.Column(db.String(45))
    address = db.Column(db.String(255))

    # pub_date = db.Column(db.DateTime)


    def __init__(self, name, number, email='liaolijiang@qq.com', address='*****'):
        self.name = name
        self.number = number
        self.email = email
        self.address = address


    @classmethod
    def add(cls, user):
        db.session.add(user)
        db.session.commit()
        # flash(u'User item was successfully created')
        return redirect(url_for('show_all'))

    @classmethod
    def delete(cls, user):
        db.session.delete(user)
        db.session.commit()

    @classmethod
    def all(cls):
        users = cls.query.all()
        return users

    @classmethod
    def search(cls, content):
        exp = '.*' + str(content) + '.*'
        logging.info(exp)
        users = cls.query.filter(User.name.like('liao%'))
        logging.info(users)
        return users





    


@app.route('/index')
def index():
    return 'hello'

@app.route('/add')
def add():
    user = User(name='liaolj', number='054040')
    User.add(user)
    users = User.all()
    return str(users)

@app.route('/show_all')
def show_all():
    users = User.query.all()
    return render_template('show_all.html', users=users)
@app.route('/submit',  methods=('GET', 'POST'))
def submit():
    form = UserForm(csrf_enabled=False)
    if form.validate_on_submit():
        name = form.name.data
        if name == None:
            logging.error('name error')
        elif name == '':
            logging.error('name == \'\'')
        logging.info(name)
        logging.info('type:<%r>' %type(name))
        number = form.number.data
        email = form.email.data
        address = form.address.data
        user = User(name, number, email, address)
        User.add(user)
        users = User.all()
        # return redirect(url_for('show_all'))
    else:
        users = None
        # form = None
    search_form = SearchForm(csrf_enabled=False)
    if search_form.validate_on_submit():
        searchText = search_form.search.data
        User.search(searchText)

    return render_template('submit.html', form=form, search_form=search_form, users = users)

def main():
    logging.info('main >>')
    Bootstrap(app)
    logging.error('Bootstrap init')
    app.run(debug=True)
    

if __name__ == '__main__':
    main()



